package com.tjy.wfx.config;

import com.tjy.wfx.WfxRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * shiro的配置类
 */
@Configuration
public class ShiroConfig {
    //1.配置拦截器
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainBefinition(){
    DefaultShiroFilterChainDefinition chain =new DefaultShiroFilterChainDefinition();
//    哪些请求可以匿名访问 (放行一些静态资源不被shiro拦截)
        chain.addPathDefinition("/static/**","anon");
    chain.addPathDefinition("/plugins/**","anon");
        chain.addPathDefinition("/user/login/**","anon");
//    除了以上请求 其他都要登录
        chain.addPathDefinition("/**","authc");
        return chain;
    }
    //2.配置安全管理器
    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(wfxRealm());
        return securityManager;
    }
    //3.配置realm
    @Bean
   public WfxRealm wfxRealm(){
        WfxRealm wfxRealm = new WfxRealm();
        wfxRealm.setCredentialsMatcher(credentialsMatcher());
        return wfxRealm;
    }
    //4.shiro生命周期配置
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }

    //5.配置bug对应的解决配置

    /**
     * setUserPreFix(false)用于解决一个奇怪的bug，在引入spring-aop情况下。
     * 在@Controller注解的方法加入@RequiresRole等shiro注解会导致该方法无法映射
     * 导入返回404 加入这个配置会解决这个bug
     * @return
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }
    //6.设置md5加密配置
    @Bean
    public HashedCredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher =new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        hashedCredentialsMatcher.setHashIterations(56);
        return hashedCredentialsMatcher;
    }
}
